var db = wx.cloud.database();
const app = getApp();
Page({
  /**
   * 页面的初始数据
   * this.data 的意思 就是当前所有数据指向
   */
  data: {
    userInfo: null,
    chickenList: [],
    currentIndex: 0,
    currentSubMenus: [],
  },
  addFood: function (e) {
    if (app.globalData.userInfo == null)
      return wx.showToast({
        title: "请先进行登录",
        icon: "none",
      });
    const item = e.currentTarget.dataset.item;
    wx.showLoading({
      title: "加载中",
    });
    db.collection("addFoodList")
      .where({
        name: item.name,
        _openid: this.data.userInfo._openid,
      })
      .get({
        success: (res) => {
          if (res.data.length === 0) {
            // 如果没有找到记录，添加新记录
            db.collection("addFoodList").add({
              data: {
                _openid: this.data.userInfo._openid,
                name: item.name,
                price: item.price,
                image: item.image,
                num: 1,
              },
              success: (res) => {
                wx.hideLoading();
              },
              fail: (err) => {
                wx.hideLoading();
              },
            });
          } else {
            // 如果找到记录，更新数量
            var existingItem = res.data[0];
            db.collection("addFoodList")
              .doc(existingItem._id)
              .update({
                data: {
                  num: existingItem.num + 1,
                },
                success: (res) => {
                  wx.hideLoading();
                },
                fail: (err) => {
                  wx.hideLoading();
                },
              });
          }
        },
        fail: (err) => {
          wx.hideLoading();
        },
      });
  },
  onCategoryClick: function (e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      currentIndex: index,
      currentSubMenus: this.data.chickenList[index].subMenus,
    });
  },
  getData() {
    db.collection("chickenList")
      .get()
      .then((res) => {
        this.setData({
          chickenList: res.data,
          currentSubMenus: res.data[0].subMenus,
        });
      });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      userInfo: app.globalData.userInfo,
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},
});
